package com.yuexun.dhdoctor.module.commun.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;


import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.AppContext;
import com.yuexun.dhdoctor.base.BaseEntity;
import com.yuexun.dhdoctor.baselistener.OnDataBackListener;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.Contract.adapter.AddMemberAdapter;
import com.yuexun.dhdoctor.module.Contract.adapter.DepartmentListAdapter;
import com.yuexun.dhdoctor.module.Contract.bean.GroupDataBean;
import com.yuexun.dhdoctor.module.Contract.bean.People;
import com.yuexun.dhdoctor.module.Contract.bean.UsersBean;
import com.yuexun.dhdoctor.module.Contract.model.impl.DepartmentModel;
import com.yuexun.dhdoctor.module.Contract.presenter.impl.DepartmentPresenter;
import com.yuexun.dhdoctor.module.Contract.ui.view.IDepartmentView;
import com.yuexun.dhdoctor.module.commun.ui.Act_Choice_Department;
import com.yuexun.dhdoctor.module.commun.ui.Act_Choice_Member;
import com.yuexun.dhdoctor.widget.EmptyLayout;
import com.yuexun.dhdoctor.widget.FixedSwipeListView;

import org.kymjs.kjframe.ui.KJFragment;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by Administrator on 2017/3/27 0027.
 */

public class Frag_Choice_Department extends KJFragment implements IDepartmentView {

    @Bind(R.id.etSearch2)
    EditText etSearch2;
    @Bind(R.id.btnSearchClear)
    ImageButton btnSearchClear;
    @Bind(R.id.searchLayout)
    LinearLayout searchLayout;
    @Bind(R.id.dept_list)
    FixedSwipeListView deptList;
    @Bind(R.id.people_list)
    FixedSwipeListView peopleList;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    private Handler handler;
    ArrayList<People> usersBeans_origin = new ArrayList<>();
    OnDataBackListener listener;

    private DepartmentPresenter presenter;
    private BaseAdapter adapter_dept;
    private AddMemberAdapter addMemberAdapter;
    ArrayList<People> peoples = new ArrayList<>();
    ArrayList<GroupDataBean> datas;
    int hospitalId;
    int oldHospitalId;
    GroupDataBean groupDataBean;

    int from;//0多选 1单选
    private int isSelectMe;//0：不能选择  1：能选择自己
    private Act_Choice_Member aty;

    public void setUsersBeans_origin(ArrayList<People> usersBeans_origin, OnDataBackListener listener, int from, int isSelectMe) {
        this.usersBeans_origin = usersBeans_origin;
        this.listener = listener;
        this.from = from;
        this.isSelectMe = isSelectMe;
    }

    public void setHospitalId(int hospitalId) {
        this.hospitalId = hospitalId;
        if (hospitalId != oldHospitalId) {
            refrshView();
        }
    }

    private void refrshView() {
        initPresent();
        oldHospitalId = hospitalId;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (aty.hospitalId != oldHospitalId) {
                hospitalId = aty.hospitalId;
                refrshView();
            }
        }
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        aty = (Act_Choice_Member) getActivity();
        View view = inflater.inflate(R.layout.frag_choice_department, null);
        ButterKnife.bind(this, view);
        initView();
        initHandle();
        presenter = new DepartmentPresenter(new DepartmentModel(), this);

        hospitalId = PreferenceHelper.readInt(getActivity(), AppConfig.USER_INFO, AppConfig.HOSPITALID);
        oldHospitalId = hospitalId;
        initPresent();

        return view;
    }

    private void initPresent() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("hospId", hospitalId + "");
        presenter.getAllDepartment(params);
    }

    void initView() {

        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            }
        });

        deptList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Bundle bundle = new Bundle();
                Intent intent = new Intent(getActivity(), Act_Choice_Department.class);
                if (from == 0) {
                    bundle.putString("departmentId", datas.get(position).getDepartment_id() + "");
                    bundle.putSerializable("usersBeans", ((Act_Choice_Member) getActivity()).usersBeans_origin);
                    bundle.putSerializable("groupDataBean", datas.get(position));
                    bundle.putString("from", from + "");
                    bundle.putInt("isSelectMe", isSelectMe);
                    intent.putExtras(bundle);
                } else {
                    bundle.putString("departmentId", datas.get(position).getDepartment_id() + "");
                    bundle.putSerializable("usersBeans", usersBeans_origin);
                    bundle.putSerializable("groupDataBean", datas.get(position));
                    bundle.putString("from", from + "");
                    bundle.putInt("isSelectMe", isSelectMe);
                    intent.putExtras(bundle);
                }
                getActivity().startActivityForResult(intent, 1);
            }
        });

        peopleList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (from == 0) {
                    if (usersBeans_origin.contains(peoples.get(position))) {
                        usersBeans_origin.remove(peoples.get(position));
                        addMemberAdapter.notifyDataSetChanged();
                        Message msg = new Message();
                        msg.what = 10003;
                        handler.sendMessage(msg);
                    } else {
                        usersBeans_origin.add(peoples.get(position));
                        addMemberAdapter.notifyDataSetChanged();
                        Message msg = new Message();
                        msg.what = 10003;
                        handler.sendMessage(msg);
                    }
                } else {
                    if (usersBeans_origin.contains(peoples.get(position))) {
                        usersBeans_origin.remove(peoples.get(position));
                        addMemberAdapter.notifyDataSetChanged();
                        Message msg = new Message();
                        msg.what = 10003;
                        handler.sendMessage(msg);
                    } else {
                        usersBeans_origin.clear();
                        usersBeans_origin.add(peoples.get(position));
                        addMemberAdapter.notifyDataSetChanged();
                        Message msg = new Message();
                        msg.what = 10003;
                        handler.sendMessage(msg);
                    }
                }
            }
        });

        etSearch2.addTextChangedListener(new TextWatcher() {
            boolean hasPadding = true;

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
                if (TextUtils.isEmpty(s) && !hasPadding) {
                    Message msg = new Message();
                    msg.what = 10002;
                    handler.sendMessage(msg);

                    hasPadding = true;
                } else if (!TextUtils.isEmpty(s) && hasPadding) {
                    Message msg = new Message();
                    msg.what = 10001;
                    handler.sendMessage(msg);

                    hasPadding = false;
                }

                if (addMemberAdapter != null)
                    addMemberAdapter.getMyFilter(null == s ? "" : s.toString());

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (etSearch2.getText().toString().length() == 0) {
                    searchLayout.setVisibility(View.VISIBLE);
                    deptList.setVisibility(View.VISIBLE);
                } else {
                    deptList.setVisibility(View.GONE);
                    searchLayout.setVisibility(View.GONE);
                }
            }
        });

    }

    void initHandle() {
        handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 10001: // 搜索有文字的的时候
                        btnSearchClear.setVisibility(View.VISIBLE);
                        break;
                    case 10002: // 搜索没文字的的时候
                        btnSearchClear.setVisibility(View.INVISIBLE);
                        break;
                    case 10003:
                        if (listener != null) {
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("usersBeans", usersBeans_origin);
                            listener.showData(bundle);
                        }
                        break;
                    case 10004:
                        break;
                    case 10005:
                        break;
                    default: // 默认消息处理

                        break;
                }
            }
        };
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        return null;
    }

    @OnClick({R.id.btnSearchClear})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnSearchClear:
                etSearch2.setText("");
                break;
        }
    }

    @Override
    public void showGroupDatas(final BaseEntity<GroupDataBean> groupBean) {
        if ("200".equals(groupBean.getStatus())) {
            groupDataBean = groupBean.getDatas().get(0).getChildDepartments().get(0);
            refresh(groupDataBean);
        } else {
            ViewInject.toast("获取数据失败");
        }
    }

    private void refresh(GroupDataBean groupDataBean) {
        if (emptyLayout != null) {
            emptyLayout.dismiss();
        }
        datas = groupDataBean.getChildDepartments();

        List<UsersBean> usersBeen = groupDataBean.getUsers();
        adapter_dept = new DepartmentListAdapter(AppContext.getInstance(), datas, isSelectMe);
        deptList.setAdapter(adapter_dept);

        peoples.clear();
        if (usersBeen != null && usersBeen.size() > 0) {
            for (int i = 0; i < usersBeen.size(); i++) {
                People people = new People();
                people.setUserId(usersBeen.get(i).getUser_id());
                people.setUserName(usersBeen.get(i).getUser_name());
                people.setJobNum(usersBeen.get(i).getJobNum());
                peoples.add(people);
            }
        }

        if (addMemberAdapter == null) {
            addMemberAdapter = new AddMemberAdapter(AppContext.getInstance(), peoples, usersBeans_origin, handler, isSelectMe, peopleList, from);
            peopleList.setAdapter(addMemberAdapter);
        } else {
            addMemberAdapter.setData(peoples);
        }

    }

}
